from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import  datetime
import random

random.seed(datetime.datetime.now())
def getLinks(articleUrl):
    html=urlopen("http://en.wikipedia.org"+articleUrl)
    bsObj=BeautifulSoup(html,"html.parser")
    return bsObj.find("div",{"id":"bodyContent"}).findAll("a",href=re.compile("^(/wiki/)((?!:).)*$"))

links = getLinks("/wiki/Kevin_Bacon")
f = open('linkName.txt','w')
while len(links) > 0:
    newArticle = links[random.randint(0,len(links)-1)].attrs["href"]
    # random.randint()随机生一个整数int类型，可以指定这个整数的范围，同样有上限和下限值
    f.write(newArticle)
    links = getLinks(newArticle)
    f.flush()
f.close()
